﻿using System.Diagnostics;

namespace 多线程
{
    internal class Program
    {
        static void Main(string[] args)
        {
            TestThread();
            TestTask();

            Console.WriteLine("Hello, World!");
        }

        #region 使用Thread

        static void TestThread()
        {
            // 不带参数
            Thread thread = new Thread(() =>
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();  

                Console.WriteLine($"Hello, thread 1! {Thread.CurrentThread.ManagedThreadId}");

                stopwatch.Stop();
                Console.WriteLine($"{stopwatch.ElapsedMilliseconds}");
            });

            thread.Start();

            // 带参数
            Thread thread1 = new Thread(PMethod);
            thread1.Start("aaaa");

        }

        public static void PMethod(object str)
        {
            Console.WriteLine($"{str} ==> {Thread.CurrentThread.ManagedThreadId}");
        }

        #endregion



        #region 使用Task

        /// <summary>
        /// task 对thread类进行了封装，用task启动线程的4中方式
        /// </summary>
        static void TestTask()
        {

            Task task = new Task(() =>
            {
                Task.Delay(1000);

                Console.WriteLine($"Hello, task1!,{Thread.CurrentThread.ManagedThreadId}");
            });

            task.Start();


            // 线程已经启动了
            Task.Run(() => Console.WriteLine($"Hello, task2!,{Thread.CurrentThread.ManagedThreadId}"));


            //
            TaskFactory f = new TaskFactory();

            f.StartNew(() =>
            {
                Console.WriteLine($"Hello, task3!,{Thread.CurrentThread.ManagedThreadId}");
            });

            Task.Factory.StartNew(() => Console.WriteLine($"Hello, task4!,{Thread.CurrentThread.ManagedThreadId}"));
        }


        #endregion
    }
}
